package com.halden.TRPG.filter;

import com.alibaba.fastjson.JSON;
import com.halden.TRPG.common.CodeEnum;
import com.halden.TRPG.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String method = request.getMethod();
        //预请求放行
        if (StringUtils.hasText(method) && method.equals("OPTIONS")){
            return true;
        }
        //检查token
        String token = request.getHeader("Authorization");
        log.info(token);
        if (!StringUtils.hasText(token) || !JwtUtil.check(token)){
            response.setStatus(301);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write(JSON.toJSONString(CodeEnum.NOT_LOGIN_EXCEPTION));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
